package blackberryApp;

import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.util.Hashtable;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

import blackberryAppCom.BBApp_Common;
import blackberryAppBus.BBApp_MobilBusiness;

/**
 * Servlet implementation class BBApp_cMobilScreen
 */
public class BBApp_cMobilScreen extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public BBApp_cMobilScreen() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		BBApp_MobilBusiness lObjBBApp_MobilBusiness = new BBApp_MobilBusiness();
		
		int lIntHidMode = BBApp_Common.fnChkInteger(BBApp_Common.fnGetValue(req.getParameter("hidMode")));
		if (lIntHidMode == 0) {
			lIntHidMode = 1;
		}
		
		String strNoPolis		= "";
		if (req.getParameter("hidNoPolis") != null) {
			strNoPolis = BBApp_Common.fnGetValue(req.getParameter("hidNoPolis"));
		}
		String strNoPlat		= "";
		if (req.getParameter("hidNoPlat") != null) {
			strNoPlat = BBApp_Common.fnGetValue(req.getParameter("hidNoPlat"));
		}
		String strNoRangka		= "";
		if (req.getParameter("hidNoRangka") != null) {
			strNoRangka = BBApp_Common.fnGetValue(req.getParameter("hidNoRangka"));
		}
		String strNoMesin		= "";
		if (req.getParameter("hidNoMesin") != null) {
			strNoMesin = BBApp_Common.fnGetValue(req.getParameter("hidNoMesin"));
		}
		String strRecNo		= "";
		if (req.getParameter("hidRecNo") != null) {
			strRecNo = BBApp_Common.fnGetValue(req.getParameter("hidRecNo"));
//			BBApp_Common.fnWriteLog("BBApp_cMobilScreen","fnRetStatusKlaim: ","> strRecNo: " + strRecNo);
		}
		String strMaxNo		= "";
		if (req.getParameter("hidMaxNo") != null) {
			strMaxNo = BBApp_Common.fnGetValue(req.getParameter("hidMaxNo"));
//			BBApp_Common.fnWriteLog("BBApp_cMobilScreen","fnRetStatusKlaim: ","> strMaxNo: " + strMaxNo);
		}
		
		BBApp_cjbBBApp lObjBBApp_cjbBBApp = new BBApp_cjbBBApp();
		lObjBBApp_cjbBBApp.setStrNoPlat(strNoPlat.toUpperCase());
		lObjBBApp_cjbBBApp.setStrNoPolis(strNoPolis.toUpperCase());
		lObjBBApp_cjbBBApp.setStrNoRangka(strNoRangka.toUpperCase());
		lObjBBApp_cjbBBApp.setStrNoMesin(strNoMesin.toUpperCase());
		lObjBBApp_cjbBBApp.setStrRecNo(strRecNo);
		lObjBBApp_cjbBBApp.setStrMaxNo(strMaxNo);
		
		switch (lIntHidMode) {
			case 1: // dari blackberry, login SIMAS MOBIL, plat dan polis
				try {
					//BBApp_Common.fnWriteLog("BBApp_cMobilScreen","Case","1");
					
					// detil pemilik
					BBApp_cjbBBApp lObjBBApp_cjbBBAppResult = new BBApp_cjbBBApp();
					if (strNoPolis.trim().length() > 0) {
						lObjBBApp_cjbBBAppResult = lObjBBApp_MobilBusiness.fnRetDetPesertaPolis(lObjBBApp_cjbBBApp);
					} else if (strNoPlat.trim().length() > 0) {
						lObjBBApp_cjbBBAppResult = lObjBBApp_MobilBusiness.fnRetDetPesertaPlatRangkaMesin(lObjBBApp_cjbBBApp);
					} else if (strNoRangka.trim().length() > 0) {
						lObjBBApp_cjbBBAppResult = lObjBBApp_MobilBusiness.fnRetDetPesertaPlatRangkaMesin(lObjBBApp_cjbBBApp);
					} else if (strNoMesin.trim().length() > 0) {
						lObjBBApp_cjbBBAppResult = lObjBBApp_MobilBusiness.fnRetDetPesertaPlatRangkaMesin(lObjBBApp_cjbBBApp);
					} 
					
					String lStrNoPlat = lObjBBApp_cjbBBAppResult.getStrNoPlat();
					//String lStrNoPolis = lObjBBApp_cjbBBAppResult.getStrNoPolis();
					lObjBBApp_cjbBBAppResult.setStrRecNo(strRecNo);
					lObjBBApp_cjbBBAppResult.setStrMaxNo(strMaxNo);
					
					// detil klaim
					//if ((lStrNoPlat.trim().length() > 0) || (lStrNoPolis.trim().length() > 0)) {
					if (lStrNoPlat.trim().length() > 0) {
						Hashtable htResult = new Hashtable();
						htResult = lObjBBApp_MobilBusiness.fnRetStatusKlaim(lObjBBApp_cjbBBAppResult);
						if (htResult.size() > 0) {
							req.getSession().setAttribute("lHstDataClaim", (Hashtable) htResult.get("Register"));
							
							strRecNo = (String) htResult.get("RecNo");
//							BBApp_Common.fnWriteLog("BBApp_cMobilScreen","fnRetStatusKlaim: ",">>> strRecNo: " + strRecNo);
							lObjBBApp_cjbBBAppResult.setStrRecNo(strRecNo);
							
							strMaxNo = (String) htResult.get("MaxNo");
//							BBApp_Common.fnWriteLog("BBApp_cMobilScreen","fnRetStatusKlaim: ",">>> strMaxNo: " + strMaxNo);
							lObjBBApp_cjbBBAppResult.setStrMaxNo(strMaxNo);
						}
					}
					
					XMLOutput(req, resp, lObjBBApp_cjbBBAppResult);
					
//					req.setAttribute("lObjBBApp_cjbBBApp",lObjBBApp_cjbBBAppResult);
//					fnForwardToJsp(req, resp, "/BBApp_MobilScreen.jsp");
					return;
				}
				catch(Exception e) {
					BBApp_Common.fnWriteLog("BBApp_cMobilScreen","BBApp_cMobilScreen(case 1) : ","Exception : "+e);
					req.setAttribute("ErrorCode","2000");
					//getServletConfig().getServletContext().getRequestDispatcher("/UTIL_cERRORPAGE").forward(req,resp);	
					return;
				}
				
			case 0: // Redirect to error page
				BBApp_Common.fnWriteLog("BBApp_cMobilScreen","BBApp_cMobilScreen : ","Undefined hidMode or hidMode is null : "+lIntHidMode);
				req.setAttribute("ErrorCode","2001");
				//getServletConfig().getServletContext().getRequestDispatcher("/UTIL_cERRORPAGE").forward(req,resp);
				return;
		}
	}
	
	/**
	 * fnForwardToJsp (input nama file)
	 */
	public void fnForwardToJsp(HttpServletRequest req, HttpServletResponse res, String strNamaFile)throws ServletException, IOException 
	{	
		getServletConfig().getServletContext().getRequestDispatcher(strNamaFile).forward(req,res);
		return;
	}
	
	/**
	 * XMLOutput
	 */
	public void XMLOutput(HttpServletRequest req, HttpServletResponse resp, BBApp_cjbBBApp lObjBBApp_cjbBBAppResult) {
		try {
			DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
	        DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();
	        Document doc = docBuilder.newDocument();
	        
	        String strXMLString = createXmlTree(doc, req, resp, lObjBBApp_cjbBBAppResult);
	        
	        ServletOutputStream out = resp.getOutputStream();
	        resp.setContentType("text/xml");
	        InputStream in = new ByteArrayInputStream(strXMLString.getBytes());
	        byte[] buffer = strXMLString.getBytes();
	        int intSize = in.read(buffer);
		    if (intSize != -1) {
		      out.write(buffer, 0, intSize);
		    }
		    
		    in.close();
		    out.flush();
		}
		catch (Exception exp) {
			BBApp_Common.fnWriteLog("BBApp_cMobilScreen","BBApp_cMobilScreen(XMLOutput) : ","Exception : "+exp);
		}
	}
	
	/**
	 * createXmlTree
	 */
	public String createXmlTree(Document doc, HttpServletRequest req, HttpServletResponse resp, BBApp_cjbBBApp lObjBBApp_cjbBBAppResult) throws Exception {
        //This method creates an element node
		
		String strNoPolis = lObjBBApp_cjbBBAppResult.getStrNoPolis();
		String strNamaPemilik = lObjBBApp_cjbBBAppResult.getStrNama();
		String strNoPlat = lObjBBApp_cjbBBAppResult.getStrNoPlat();
		String strNoRangka = lObjBBApp_cjbBBAppResult.getStrNoRangka();
		String strNoMesin = lObjBBApp_cjbBBAppResult.getStrNoMesin();
		String strRecNo = lObjBBApp_cjbBBAppResult.getStrRecNo();
		String strMaxNo = lObjBBApp_cjbBBAppResult.getStrMaxNo();
		
		Element eRoot = doc.createElement("GlobalInfo");
		doc.appendChild(eRoot);
		
		Element ePeserta = doc.createElement("Peserta");
		eRoot.appendChild(ePeserta);
		
			Element eNoPolis = doc.createElement("NoPolis");
			ePeserta.appendChild(eNoPolis);
			Text txtNoPolis = doc.createTextNode(strNoPolis);
			eNoPolis.appendChild(txtNoPolis);
			
			Element eNamaPemilik = doc.createElement("NamaPemilik");
			ePeserta.appendChild(eNamaPemilik);
			Text txtNamaPemilik = doc.createTextNode(strNamaPemilik);
			eNamaPemilik.appendChild(txtNamaPemilik);
			
			Element eNoPlat = doc.createElement("NoPlat");
			ePeserta.appendChild(eNoPlat);
			Text txtNoPlat = doc.createTextNode(strNoPlat);
			eNoPlat.appendChild(txtNoPlat);
			
			Element eNoRangka = doc.createElement("NoRangka");
			ePeserta.appendChild(eNoRangka);
			Text txtNoRangka = doc.createTextNode(strNoRangka);
			eNoRangka.appendChild(txtNoRangka);
			
			Element eNoMesin = doc.createElement("NoMesin");
			ePeserta.appendChild(eNoMesin);
			Text txtNoMesin = doc.createTextNode(strNoMesin);
			eNoMesin.appendChild(txtNoMesin);
		
		if (req.getSession().getAttribute("lHstDataClaim") != null) {
			
			BBApp_Common.fnWriteLog("BBApp_cMainScreen","BBApp_cMainScreen(XMLOutput) : ","createXmlTree, data klaim");
			
			Hashtable htDataKlaim = (Hashtable) req.getSession().getAttribute("lHstDataClaim");
			String[] strHstDataClaim = (String[]) htDataKlaim.get(String.valueOf(1));
			String lObjNoKlaim = strHstDataClaim[0];
			String lObjTglRegister = BBApp_Common.fnGetDateDDMMMYYYY(strHstDataClaim[1]);
			String lObjTglLapor = BBApp_Common.fnGetDateDDMMMYYYY(strHstDataClaim[2]);
			String lObjNoPlat = strHstDataClaim[3];
			String lObjBengkel = strHstDataClaim[4];
			String lObjKondisi = strHstDataClaim[5];
			String lObjKendala = strHstDataClaim[6];
			String lObjKeterangan = strHstDataClaim[7];
			String lObjStatusKlaim  = strHstDataClaim[8];
			
			
			Element eKlaim = doc.createElement("Klaim");
			eRoot.appendChild(eKlaim);
			
				Element eNoKlaim = doc.createElement("NoKlaim");
				eKlaim.appendChild(eNoKlaim);
				Text txtNoKlaim = doc.createTextNode(lObjNoKlaim);
				eNoKlaim.appendChild(txtNoKlaim);
				
				Element eTglRegister = doc.createElement("TglRegister");
				eKlaim.appendChild(eTglRegister);
				Text txtTglRegister = doc.createTextNode(lObjTglRegister);
				eTglRegister.appendChild(txtTglRegister);
				
				Element eTglLapor = doc.createElement("TglLapor");
				eKlaim.appendChild(eTglLapor);
				Text txtTglLapor = doc.createTextNode(lObjTglLapor);
				eTglLapor.appendChild(txtTglLapor);
				
				Element eNoPlatK = doc.createElement("NoPlat");
				eKlaim.appendChild(eNoPlatK);
				Text txtNoPlatK = doc.createTextNode(lObjNoPlat);
				eNoPlatK.appendChild(txtNoPlatK);
				
				Element eBengkel = doc.createElement("Bengkel");
				eKlaim.appendChild(eBengkel);
				Text txtBengkel = doc.createTextNode(lObjBengkel);
				eBengkel.appendChild(txtBengkel);
				
				Element eKondisi = doc.createElement("Kondisi");
				eKlaim.appendChild(eKondisi);
				Text txtKondisi = doc.createTextNode(lObjKondisi);
				eKondisi.appendChild(txtKondisi);
				
				Element eKendala = doc.createElement("Kendala");
				eKlaim.appendChild(eKendala);
				Text txtKendala = doc.createTextNode(lObjKendala);
				eKendala.appendChild(txtKendala);
				
				Element eKeterangan = doc.createElement("Keterangan");
				eKlaim.appendChild(eKeterangan);
				Text txtKeterangan = doc.createTextNode(lObjKeterangan);
				eKeterangan.appendChild(txtKeterangan);
				
				Element eStatusKlaim = doc.createElement("StatusKlaim");
				eKlaim.appendChild(eStatusKlaim);
				Text txtStatusKlaim = doc.createTextNode(lObjStatusKlaim);
				eStatusKlaim.appendChild(txtStatusKlaim);
				
				Element eMaxNo = doc.createElement("MaxNo");
				eKlaim.appendChild(eMaxNo);
				Text txtMaxNo = doc.createTextNode(strMaxNo);
				eMaxNo.appendChild(txtMaxNo);
				
				Element eRecNo = doc.createElement("RecNo");
				eKlaim.appendChild(eRecNo);
				Text txtRecNo = doc.createTextNode(strRecNo);
				eRecNo.appendChild(txtRecNo);
				
		}
			
		//TransformerFactory instance is used to create Transformer objects. 
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        
        // create string from xml tree
        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);
        DOMSource source = new DOMSource(doc);
        transformer.transform(source, result);
        String xmlString = sw.toString();

        // bikin file dan tulis isi nya 
      File file = new File("c:/newMBU.xml");
      BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
      bw.write(xmlString);
      bw.flush();
      bw.close();
        
        return xmlString;
    }
	
}
